import { Button, Flex, Form, Input, Select } from "antd"
import { useSelector } from "react-redux"
import type { ROOTSTATE } from "../store"
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Title } from "../components/Title"
import { Editor, Toolbar } from "@wangeditor/editor-for-react"
import { useEffect, useState } from "react"
import type { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor"
import type { RESPONSE } from "../types/base"
import { useNavigate } from "react-router"
import type { IssueForm } from "../types/issue"
import { reqAddIssue } from "../api/issue"

export const IssueEdit = ()=>{
    const typeList = useSelector((state: ROOTSTATE) => state.typeStore.typeList)
    const options = typeList.map((item) => {
        return {
            value: item._id,
            label: item.typename
        }
    })
    // 富文本
    // editor 实例
    const [editor, setEditor] = useState<IDomEditor | null>(null)
    // 编辑器内容
    const [html, setHtml] = useState('<p>请输入</p>')
    // 工具栏配置
    const toolbarConfig: Partial<IToolbarConfig> = {}
    // 编辑器配置
    type InsertFnType = (
        url: string,
        alt: string | null,
        href: string | null
    ) => void
    const editorConfig: Partial<IEditorConfig> = {
        MENU_CONF:{
            uploadImage:{
                fieldName:"file",
                server: "/dev-api/api/upload",
                customInsert(res: RESPONSE<string>, insertFn: InsertFnType) {
                    // TS 语法
                    // customInsert(res, insertFn) {                  // JS 语法
                    // res 即服务端的返回结果

                    // 从 res 中找到 url alt href ，然后插入图片
                    console.log(res);
                    insertFn(res.data, "", "")
                },
            },
        },
        placeholder: '请输入内容...',
    }
    // 及时销毁 editor ，重要！
    useEffect(() => {
        return () => {
            if (editor == null) return
            editor.destroy()
            setEditor(null)
        }
    }, [editor])
    const user = useSelector((state: ROOTSTATE) => state.userStore.user)
    const navigate = useNavigate()
    const sendIssue = async (Issue: IssueForm) => {
        await reqAddIssue(Issue)
        // 跳转到主页
        navigate("/issue")
    }
    //富文本结束
    return (
        <Flex vertical gap={30}>
            <Title title="提问模块"></Title>
            <Form
              layout="vertical"
              onFinish={(value) => {
                sendIssue({
                    ...value,
                    content: html,
                    userId: user._id,
                })
              }}
              >
                <Form.Item
                    label="文章标题"
                    name="title"
                    rules={[
                        {required: true, message: "填写文章标题"},
                        {max: 50, message: "最大长度为50"}
                    ]}>
                    <Input></Input>
                </Form.Item>
                <Form.Item 
                    label="文章类别"
                    name="typeId"
                    rules={[{ required:true,message:"选择文章类别"}]}>
                    <Select options={options} style={{ width: 150 }}></Select>
                </Form.Item>
                <Form.Item label="文章内容">
                    <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
                        <Toolbar
                            editor={editor}
                            defaultConfig={toolbarConfig}
                            mode="default"
                            style={{ borderBottom: '1px solid #ccc' }}
                        />
                        <Editor
                            defaultConfig={editorConfig}
                            value={html}
                            onCreated={setEditor}
                            onChange={(editor) => setHtml(editor.getHtml())}
                            mode="default"
                            style={{ height: '500px', overflowY: 'hidden' }}
                        />
                    </div>
                    {/* <div>{html}</div> */}
                </Form.Item>
                <Form.Item label={null}>
                    <Flex gap={30}>
                        <Button type="primary" htmlType="submit">确认发布</Button>
                        <Button>重置</Button>
                    </Flex>
                </Form.Item>
            </Form>
        </Flex>
    )
}